package zhoug.demo.zui.ui;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;

import zhoug.zui.input.ZUIInputView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * @Author: zhoug
 * @Date: 2024-07-10
 * @Description:
 */
@SuppressLint("UseSwitchCompatOrMaterialCode")
public abstract class ZUIInputViewBaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onCreated(savedInstanceState);
        init();
    }

    protected void init() {
         Switch enableSwitchView = getEnableSwitchView();
        if(enableSwitchView!=null){
            enableSwitchView.setOnCheckedChangeListener((btn, isCheck) -> {
                findInputView(view -> {
                    view.setEnabled(!isCheck);
                });
            });
        }

        Switch errorSwitchView = getErrorSwitchView();
        if(errorSwitchView!=null){
            errorSwitchView.setOnCheckedChangeListener((btn, isCheck) -> {
                findInputView(view -> {
                    view.setError(isCheck);
                });
            });
        }
    }

    protected abstract void onCreated(@Nullable Bundle savedInstanceState);

    protected abstract ViewGroup getContentView();

    protected abstract Switch getEnableSwitchView();

    protected abstract Switch getErrorSwitchView();


    protected void findInputView(Function<ZUIInputView> function) {
        ViewGroup contentView = getContentView();
        if (contentView == null) return;
        int childCount = contentView.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = contentView.getChildAt(i);
            if (child instanceof ZUIInputView inputView) {
                function.apply(inputView);
            }
        }
    }

    protected interface Function<T> {
        void apply(T t);
    }

}
